/**
 * Created by msi on 2018/4/9.
 * 用户登录前端逻辑
 */

require("./user-login.css");
require("page/common/nav-simple/nav-simple.js");
var _user = require("service/user-service.js");
var _mm = require("util/mm.js");

var  formError = {
    show : function(errMsg){
        $(".error-item").show().find(".err-msg").text(errMsg);
    },
    hide : function(){
        $(".error-item").hide().find(".err-msg").text("");
    }
}

var page = {
    init : function(){
      this.bindEvent();
    },
    bindEvent : function(){
        var _this = this;
        $("#submit").click(function(){
            _this.submit();
        });
        $(".user-content").keyup(function(e){
            if(e.keyCode === 13){
                _this.submit();
            }
        });
    },
    //提交登录信息表单
    submit : function(){
        var fromData = {
            username : $.trim($("#username").val()),
            password : $.trim($("#password").val()),
        };
        var validateResult = this.formValidate(fromData);
        if(validateResult.status){//验证通过
            formError.hide();
            _user.login(fromData,
                function(res){//登录成功的回调函数
                    //跳转
                    window.location.href = _mm.getUrlParam("redirect" ) || "./index.html";
                },
                function(err){//登录异常的回调函数
                    //显示错误信息
                    formError.show(err.msg);
                }
            );
        }else{//验证失败
            //错误提示
            formError.show(validateResult.msg);
        }
    },
    //表单字段验证
    formValidate : function(formData){
        var result = {
            status : false,
            msg : ""
        };
        if(!_mm.validate(formData.username,"require")){
            result.msg = "用户名不能为空";
            return result;
        }
        if(!_mm.validate(formData.password,"require")){
            result.msg = "密码不能为空";
            return result;
        }
        //通过验证返回，正确提示
        result.status = true;
        result.msg = "验证通过";
        return result;
    }

};
$(function(){
    page.init();
});